package com.hjh.thread.condition.condition2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class QueueManager {

    private int maxSize = 10;

    private QueueManager(){

    }

    private static class QueueManagerHandler{
        private static  QueueManager instance = new QueueManager();
    }

    public static QueueManager getInstance(){
        return QueueManagerHandler.instance;
    }

    private List<String> queueList = new ArrayList<>();

    private Lock lock = new ReentrantLock();

    private Condition producerCondition = lock.newCondition();
    private Condition consumerCondition = lock.newCondition();


    public void add(String item){

        lock.lock();
        try {
            while (queueList.size() >= 100){
                System.out.println("===========>add await");

                //添加的条件等待
                producerCondition.await();
            }

            System.out.println("===========>add value:"+ item);

            queueList.add(item);

            //消费锁通知
            consumerCondition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public String quit(){

        lock.lock();
        try {
            System.out.println("=======>");
            while (queueList.size() <= 0){
                consumerCondition.await();
            }

            String item = queueList.remove(0);

            producerCondition.signalAll();

            return item;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }
}
